<?php
namespace app\index\controller;
use app\common\controller\Frontend;
use think\Lang;
use think\Cache;
use function GuzzleHttp\Promise\all;
//require_once './../vendor/xunsearch/sdk/php/lib/XS.php';
vendor('xunsearch.sdk.php.lib.XS');
/**
 * Ajax异步请求接口
 * @internal
 */
class Search extends Frontend
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];
    protected $layout = '';
    public function index()
    {
        $keyword = $this->request->request('kw');
        if ($keyword) {
            Cache::set('keyword',$keyword);
        }

        $nostart = $this->request->request('start');
        $this->articles = new \app\admin\model\Articles;
        $this->xs = new \XS('dev_blog'); // 这里是关键, XS这个类不在Home\Controller空间中,是在公共空间,所以加反斜杠就不会提示class xxx not found 错误了
        $search = $this->xs->search;
        $query = Cache::get('keyword');
        $total = $search->getDbTotal();
        $search->setQuery($query)->setFuzzy()->addweight('article_title', 'article_content')->setLimit(10,$nostart);
        $docs = $search->search();
        $count = $search->getLastCount();
        $corrected = $search->getCorrectedQuery();
        if (count($corrected) !== 0) {
            // 有纠错建议，列出来看看；此情况就会得到 "测试" 这一建议
            echo "您是不是要找：\n";
            foreach ($corrected as $word) {
                echo $word . "\n";
            }
        }
        $words = $search->getRelatedQuery();
        //$words = $search->getHotQuery(); // 获取前 6 个总热门搜索词
        //$words = $search->getHotQuery(10, 'lastnum'); // 获取前 10 个上周热门词
        echo "相关词：\n";
        foreach($words as $word){
            echo $word . "\n";
        }
        // dump($count);
        // dump($docs);
        $url = $this->request->request('url');
        $sortid = $this->request->request('sortid')?$this->request->request('sortid'):"";
        $this->comments = new \app\admin\model\Comments;
        $this->articles = new \app\admin\model\Articles;
        $this->sorts = new \app\admin\model\Sorts;
        //文章列表end
        //热门列表
       $hotlist = $this->articles->hotarticlelist();
        //分类列表
        $topsortslist = $this->sorts->gettopsortslist();
        $getnowdate=new \app\index\controller\Common();
        $category=$this->sorts->where('id',$sortid)->find();
        // 模板变量赋值
        $this->assign('articleslist', $docs);
        $this->assign('count', $count);
        $this->assign('hotlist', $hotlist);
        $this->assign('topsortslist', $topsortslist);
        $this->assign('category', $category);
        $this->assign('nowdate', $getnowdate->getnowdate());
        // 渲染模板输出
        if($this->request->isAjax()){
            return jsonp();
        }
        return $this->view->fetch();
    }
}
